<template>
  <el-dialog
    v-model="dialogVisible"
    title="修改密码"
    width="500px"
  >
    <el-form 
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input 
          v-model="form.oldPassword" 
          type="password" 
          show-password
          placeholder="请输入当前密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input 
          v-model="form.newPassword" 
          type="password" 
          show-password
          placeholder="请输入新密码"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input 
          v-model="form.confirmPassword" 
          type="password" 
          show-password
          placeholder="请再次输入新密码"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'ChangePasswordDialog',
  props: {
    modelValue: Boolean
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    const formRef = ref(null)
    const dialogVisible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })
    
    const form = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== form.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    
    const rules = reactive({
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validatePass, trigger: 'blur' }
      ]
    })
    
    const handleSubmit = () => {
      formRef.value.validate(valid => {
        if (valid) {
          // 模拟API调用
          setTimeout(() => {
            ElMessage.success('密码修改成功')
            emit('success')
            dialogVisible.value = false
          }, 500)
        }
      })
    }
    
    return {
      formRef,
      dialogVisible,
      form,
      rules,
      handleSubmit
    }
  }
}
</script>